﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Kernelx.Contexts.Newtonsoft
{
    using LimitDict = Dictionary<string, object>;

    internal class DictJsonConverter : JsonConverter<LimitDict>
    {
        public override LimitDict ReadJson(JsonReader reader, Type objectType, LimitDict existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var dict = new LimitDict();
            var obj = JObject.Load(reader);
            foreach (var item in obj)
                dict.Add(item.Key, item.Value.ToString());
            return dict;
        }
        public override void WriteJson(JsonWriter writer, LimitDict value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
            }
            else
            {
                writer.WriteStartObject();
                foreach (var kv in value)
                {
                    var val = kv.Value;
                    writer.WritePropertyName(kv.Key);
                    if (val == null)
                        writer.WriteNull();
                    else
                        serializer.Serialize(writer, val);
                }
                writer.WriteEndObject();
            }
        }
    }


}
